<template>
  <div class="xiaobu-container" v-closeSelect="'window'">
    <el-form ref="queryForm" :model="queryParams" :inline="true" class="search-form clearfix">
      <el-form-item class="search-field fl five-per-row" label="角色名称" prop="roleName">
        <el-input v-model.trim="queryParams.roleName" placeholder="请输入角色名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item class="search-field fl five-per-row" label="状态" prop="status">
        <el-select-dict dictType="STATUS" clearable placeholder="请选择状态" v-model="queryParams.status"
          @dictChange="handleQuery"></el-select-dict>
      </el-form-item>
      <el-form-item class="search-field fl five-per-row" label="创建时间" prop="beginTime">
        <el-date-picker v-model="dateRange" value-format="yyyy-MM-dd HH:mm:ss" type="daterange" @change="handleQuery"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>

      <el-form-item class="fr">
        <el-button plain @click="resetQuery">重 置</el-button>
        <el-button type="primary" @click="handleQuery">查 询</el-button>
      </el-form-item>
    </el-form>
    <div class="table-wrap">
      <div class="table-control-box">
        <el-button v-hasPermi="['system:role:create']" type="primary" plain icon="el-icon-plus" size="mini"
          @click="handleAdd">新增</el-button>
        <el-button v-hasPermi="['system:role:update']" type="success" plain icon="el-icon-edit" size="mini"
          :disabled="single" @click="handleUpdate">编辑</el-button>
        <el-button v-hasPermi="['system:role:delete']" type="danger" plain icon="el-icon-delete" size="mini"
          :disabled="multiple" @click="handleBatchDelete">删除</el-button>
      </div>
      <div class="table-box">
        <el-table ref="roleTable" :class="{ 'empty': list.length === 0 }" empty-text=" " row-key="roleId"
          v-loading="loading" :data="list" @selection-change="handleSelectionChange" @row-click="clickRow">
          <el-table-column :selectable="checkSelectable" type="selection" :reserve-selection="true" width="55"
            align="center" />
          <el-table-column label="角色名称" prop="roleName" min-width="168px" show-overflow-tooltip align="center" />
          <el-table-column-dict dictType="STATUS" dictTypeNode="tag" label="状态" align="center" prop="status"
            width="68px"></el-table-column-dict>
          <el-table-column-dict dateFormat="datetime" label="创建时间" align="center" prop="createTime"
            min-width="200px"></el-table-column-dict>
          <el-table-column-dict dateFormat="datetime" label="最后更新时间" defaultVal="--" align="center" prop="updateTime"
            min-width="200px"></el-table-column-dict>
          <el-table-column v-if="
            hasPermi([
              'system:role:status',
              'system:role:read',
              'system:role:delete',
              'system:role:user',
              'system:role:menu'
            ])
          " label="操作" align="center" fixed="right" width="300px">
            <template slot-scope="scope">
              <el-button v-hasPermi="['system:role:status']" :disabled="scope.row.isSystem === '1'" size="mini"
                :type="scope.row.status === '1' ? 'warning' : 'success'"
                @click.native.stop="handleStatusChange(scope.row)">{{ scope.row.status === "1" ? "停用" : "启用"
                }}</el-button>
              <el-button v-hasPermi="['system:role:read']" size="mini" type="primary" icon="el-icon-view"
                @click.native.stop="handleUpdate(scope.row)">查看</el-button>
              <el-button v-hasPermi="['system:role:delete']" :disabled="scope.row.isSystem === '1'" size="mini"
                type="danger" icon="el-icon-delete" @click.native.stop="handleDelete(scope.row)">删除</el-button>
              <el-button v-hasPermi="['system:role:user']" v-if="permissionLength <= 3" size="mini" type="primary"
                @click.native.stop="handleSelectUser(scope.row)">分配用户</el-button>
              <el-button v-hasPermi="['system:role:menu']" v-if="permissionLength <= 3" size="mini" type="primary" plain
                @click.native.stop="handleSelectMenu(scope.row)">分配菜单</el-button>
              <el-dropdown v-if="
                hasPermi(['system:role:user', 'system:role:menu']) &&
                permissionLength > 3
              " @command="(command) => handleCommand(command, scope.row)">
                <span class="el-dropdown-link more" @click.stop>
                  <i class="el-icon-d-arrow-right el-icon--right"></i>更多
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-hasPermi="['system:role:user']" command="handleSelectUser">分配用户</el-dropdown-item>
                  <el-dropdown-item v-hasPermi="['system:role:menu']" command="handleSelectMenu">分配菜单</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize" @pagination="getList" />
      </div>
    </div>

    <!-- 添加或编辑对话框 -->
    <role-dialog ref="roleDialog" :title="baseForm.roleId ? (isUpdate ? '编辑角色' : '查看角色') : '新增角色'" :visible.sync="open"
      :modal-append-to-body="false" :close-on-click-modal="false" :isUpdate="isUpdate" :baseForm="baseForm"
      @close="open = false" @successs="getList" width="1024px"></role-dialog>

    <select-user :title="selectUserTitle" ref="roleUser" width="1000px" :visible.sync="showSelectUser"
      @close="showSelectUser = false" :modal-append-to-body="true" :append-to-body="true" :close-on-click-modal="false"
      :roleId="selectUserRoleId"></select-user>
    <select-menu :title="selectMenuTitle" width="666px" :visible.sync="showSelectMenu" @close="showSelectMenu = false"
      :modal-append-to-body="true" :append-to-body="true" :close-on-click-modal="false"
      :roleId="selectMenuRoleId"></select-menu>
  </div>
</template>

<script>
import { roleApi } from "@/api"
import RoleDialog from "./components/role-dialog.vue"
import SelectMenu from "./components/select-menu.vue"
import SelectUser from "./components/select-user.vue"
export default {
  name: "systemRoleManage",
  components: {
    RoleDialog,
    SelectMenu,
    SelectUser
  },
  data() {
    return {
      selectUserTitle: "", // 分配用户标题
      selectMenuTitle: "", // 分配菜单标题
      showSelectUser: false, // 是否显示分配用户
      showSelectMenu: false, // 是否显示选中菜单页面弹框
      selectMenuRoleId: "", // 选择分配菜单时 操作的角色id
      selectUserRoleId: "", // 选择分配用户时 操作的角色id
      isUpdate: false, // 是否是编辑
      //搜索条件参数
      queryParams: {
        roleName: "", //角色名称
        status: "", // 状态
        beginTime: "",
        endTime: "",
        pageNum: 1,
        pageSize: 10
      },
      dateRange: [],
      list: [],
      selection: [], //选中的项
      loading: false,
      total: 0,
      roleList: [],

      // 非单个禁用
      single: true,
      // 非多个禁用(0个禁用)
      multiple: true,

      open: false,
      // 表单参数
      baseForm: {
        roleName: "", // 角色名
        order: 1, // 排序
        isSystem: "0", // 是否系统预设角色 1 是 0 否
        remark: "" // 备注
      }
    }
  },
  computed: {
    // 五个按钮权限中 有多少个按钮权限
    permissionLength() {
      const permissionList = this.$store.getters.permissionList
      const list = [
        "system:role:status",
        "system:role:read",
        "system:role:delete",
        "system:role:user",
        "system:role:menu"
      ]
      let num = 0
      for (let i = 0; i < list.length; i++) {
        const item = list[i]
        if (permissionList.includes(item)) {
          num++
        }
      }
      return num
    }
  },
  watch: {
    open(val) {
      if (!val) {
        this.isUpdate = false
        this.baseForm = {
          roleName: "", // 角色名
          order: 1, // 排序
          isSystem: "0", // 是否系统预设角色 1 是 0 否
          remark: "" // 备注
        }
        this.$refs.roleDialog && this.$refs.roleDialog.resetForm()
      }
    },
    showSelectMenu(val) {
      if (!val) {
        this.selectMenuRoleId = ""
        this.selectMenuTitle = ""
      }
    },
    showSelectUser(val) {
      if (!val) {
        this.selectUserRoleId = ""
        this.$refs.roleUser.clearSelection()
        this.selectUserTitle = ""
      }
    }
  },
  created() {
    //获取列表
    this.getList()
  },
  methods: {
    // 系统内设用户 禁止操作
    checkSelectable(row, index) {
      if (row.isSystem === "1") {
        return false
      } else {
        return true
      }
    },
    // 更多操作
    handleCommand(command, row) {
      if (command === "handleSelectUser") {
        this.handleSelectUser(row)
      } else if (command === "handleSelectMenu") {
        this.handleSelectMenu(row)
      }
    },
    // 选择分配用户
    handleSelectUser(row) {
      this.selectUserTitle = `分配用户（${row.roleName}）`
      this.selectUserRoleId = row.roleId
      this.showSelectUser = true
    },
    // 分配菜单
    handleSelectMenu(row) {
      this.selectMenuTitle = `分配菜单（${row.roleName}）`
      this.selectMenuRoleId = row.roleId
      this.showSelectMenu = true
    },
    //点击行
    clickRow(row) {
      //系统预设用户 不做处理
      if (row.isSystem === "1") {
        return
      }
      this.$refs.roleTable.toggleRowSelection(row)
    },
    //批量删除用户
    handleBatchDelete() {
      let str = ""
      const ids = []
      for (let i = 0; i < this.selection.length; i++) {
        const item = this.selection[i]
        ids.push(item.roleId)
        str += item.roleName
        if (i !== this.selection.length - 1) {
          str += ", "
        }
      }

      this.$modal
        .confirm('是否确认删除角色名称为"【' + str + '】"的数据项？')
        .then(function() {
          return roleApi.batchDeleteItems({ ids })
        })
        .then(() => {
          this.handleQuery()
          this.$modal.msgSuccess("批量删除角色成功")
        })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      // 清空已选项
      this.$refs.roleTable.clearSelection()
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    /** 查询角色列表 */
    getList() {
      this.loading = true
      roleApi
        .getList(this.addDateRange(this.queryParams, this.dateRange))
        .then((response) => {
          this.list = response.rows
          this.total = response.total
          this.loading = false
        })
        .catch((err) => {
          if (err?.name === "CanceledError") {
            return
          }
          this.loading = false
        })
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selection = selection
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true
      this.baseForm.order = this.total + 1
    },

    /** 编辑按钮操作 */
    handleUpdate(row) {
      if (!row.roleId) {
        this.isUpdate = true
      }
      const id = row.roleId || (this.selection[0] && this.selection[0].roleId)
      roleApi.getDetailById({ id }).then((data) => {
        this.baseForm = Object.assign(this.baseForm, data)
        this.open = true
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.roleId
      this.$modal
        .confirm('是否确认删除角色名称为"' + row.roleName + '"的数据项？')
        .then(function() {
          return roleApi.deleteItem({ id })
        })
        .then(() => {
          this.handleQuery()
          // 判断删除的项是否被勾选了
          const flag = this.selection.find((item) => item.roleId === id)
          flag && this.$refs.roleTable.toggleRowSelection(row, false)
          this.$modal.msgSuccess("删除成功")
        })
        .catch(() => { })
    },
    // 状态改变事件
    handleStatusChange(row) {
      roleApi
        .changeStatus({
          roleId: row.roleId,
          status: row.status === "1" ? "0" : "1"
        })
        .then((data) => {
          this.$modal.msgSuccess("改变状态成功")
          this.getList()
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.xiaobu-container {
  .tips {
    font-size: 24px;
    margin-left: 12px;
    color: $mainColor;
  }
}
</style>
